"""
发布管理API路由
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Dict, Any
from app.database import get_async_db
from app.schemas.publish import (
    PublishToDraftRequest, PublishToDraftResponse,
    DraftListResponse, MaterialListResponse, PublishHistoryResponse
)
from app.services.publish_service import publish_service
from app.utils.exceptions import ArticleNotFoundError, WeChatAPIError, DatabaseError
from app.utils.logger import logger

router = APIRouter(prefix="/publish", tags=["发布管理"])


@router.post("/draft", response_model=PublishToDraftResponse, summary="发布文章到草稿箱")
async def publish_to_draft(
    request: PublishToDraftRequest,
    db: AsyncSession = Depends(get_async_db)
):
    """
    发布文章到微信公众号草稿箱
    
    - **article_id**: 文章ID（必填）
    - **author**: 作者名称（可选）
    - **content_source_url**: 原文链接（可选）
    - **show_cover_pic**: 是否显示封面图（默认true）
    - **need_open_comment**: 是否开启评论（默认false）
    - **only_fans_can_comment**: 仅粉丝可评论（默认false）
    
    发布成功后会返回微信草稿ID
    """
    try:
        return await publish_service.publish_to_draft(db, request)
    
    except ArticleNotFoundError:
        raise HTTPException(status_code=404, detail="文章不存在")
    
    except WeChatAPIError as e:
        logger.error(f"微信API错误: {str(e)}")
        raise HTTPException(status_code=422, detail=f"微信API错误: {str(e)}")
    
    except DatabaseError as e:
        logger.error(f"发布文章数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="发布文章失败")
    
    except Exception as e:
        logger.error(f"发布文章未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.post("/batch/draft", summary="批量发布文章到草稿箱")
async def batch_publish_to_draft(
    article_ids: List[str],
    db: AsyncSession = Depends(get_async_db)
) -> Dict[str, Any]:
    """
    批量发布文章到微信公众号草稿箱
    
    - **article_ids**: 文章ID列表
    
    返回每篇文章的发布结果
    """
    try:
        return await publish_service.batch_publish_articles(db, article_ids)
    
    except Exception as e:
        logger.error(f"批量发布文章未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/drafts", response_model=DraftListResponse, summary="获取草稿列表")
async def get_drafts(
    offset: int = Query(0, ge=0, description="偏移量"),
    count: int = Query(20, ge=1, le=100, description="数量")
):
    """
    获取微信公众号草稿列表
    
    - **offset**: 偏移量（用于分页）
    - **count**: 返回的数量（最大100）
    """
    try:
        return await publish_service.get_draft_list(offset, count)
    
    except WeChatAPIError as e:
        logger.error(f"获取草稿列表微信API错误: {str(e)}")
        raise HTTPException(status_code=422, detail=f"微信API错误: {str(e)}")
    
    except Exception as e:
        logger.error(f"获取草稿列表未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.delete("/drafts/{draft_id}", summary="删除草稿")
async def delete_draft(draft_id: str):
    """
    删除微信公众号草稿
    
    - **draft_id**: 草稿ID
    """
    try:
        success = await publish_service.delete_draft(draft_id)
        
        if success:
            return {"success": True, "message": "草稿删除成功"}
        else:
            return {"success": False, "message": "草稿删除失败"}
    
    except WeChatAPIError as e:
        logger.error(f"删除草稿微信API错误: {str(e)}")
        raise HTTPException(status_code=422, detail=f"微信API错误: {str(e)}")
    
    except Exception as e:
        logger.error(f"删除草稿未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/materials", response_model=MaterialListResponse, summary="获取素材列表")
async def get_materials(
    material_type: str = Query("image", description="素材类型"),
    offset: int = Query(0, ge=0, description="偏移量"),
    count: int = Query(20, ge=1, le=100, description="数量")
):
    """
    获取微信公众号素材列表
    
    - **material_type**: 素材类型（image/video/audio）
    - **offset**: 偏移量（用于分页）
    - **count**: 返回的数量（最大100）
    """
    try:
        return await publish_service.get_material_list(material_type, offset, count)
    
    except WeChatAPIError as e:
        logger.error(f"获取素材列表微信API错误: {str(e)}")
        raise HTTPException(status_code=422, detail=f"微信API错误: {str(e)}")
    
    except Exception as e:
        logger.error(f"获取素材列表未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/history", response_model=List[PublishHistoryResponse], summary="获取发布历史")
async def get_publish_history(
    limit: int = Query(50, ge=1, le=200, description="返回的记录数"),
    db: AsyncSession = Depends(get_async_db)
):
    """
    获取文章发布历史
    
    - **limit**: 返回的记录数（最大200）
    
    返回已发布和发布失败的文章列表
    """
    try:
        return await publish_service.get_publish_history(db, limit)
    
    except DatabaseError as e:
        logger.error(f"获取发布历史数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="获取发布历史失败")
    
    except Exception as e:
        logger.error(f"获取发布历史未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/test/connection", summary="测试微信API连接")
async def test_wechat_connection() -> Dict[str, Any]:
    """
    测试微信公众号API连接状态
    
    返回连接测试结果和AccessToken状态
    """
    try:
        return await publish_service.test_wechat_connection()
    
    except Exception as e:
        logger.error(f"测试微信连接未知错误: {str(e)}")
        return {
            "success": False,
            "message": f"连接测试异常: {str(e)}",
            "timestamp": None
        }


@router.post("/schedule", summary="定时发布文章")
async def schedule_publish(
    article_id: str,
    publish_time: str,  # ISO格式时间字符串
    db: AsyncSession = Depends(get_async_db)
):
    """
    定时发布文章（预留接口）
    
    - **article_id**: 文章ID
    - **publish_time**: 发布时间（ISO格式）
    
    注意：此功能需要配合定时任务系统使用
    """
    # TODO: 实现定时发布功能
    return {
        "message": "定时发布功能正在开发中",
        "article_id": article_id,
        "publish_time": publish_time
    }